package com.haizhi.vp.controller;

import com.alibaba.fastjson.JSONObject;
import com.haizhi.vp.entity.*;
import com.haizhi.vp.mapper.*;
import com.haizhi.vp.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * WORD导出
 * @author fc
 * @create 2022.10.15
 */
@Controller
@RequestMapping("/report")
public class WordController {

    @Autowired
    private WordService wordService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BaseInfoMapper baseInfoMapper;
    @Autowired
    private BdImportantMatterMapper bdImportantMatterMapper;
    @Autowired
    private BdInfoMapper bdInfoMapper;
    @Autowired
    private DutyInfoMapper dutyInfoMapper;
    @Autowired
    private EmergencyResponseInfoMapper emergencyResponseInfoMapper;
    @Autowired
    private LineFailureInfoMapper lineFailureInfoMapper;
    @Autowired
    private OnlineInspectionInfoMapper onlineInspectionInfoMapper;
    @Autowired
    private TomorrowBdInfoMapper tomorrowBdInfoMapper;
    @Autowired
    private TomorrowDutyInfoMapper tomorrowDutyInfoMapper;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    @PostMapping("/save")
    @ResponseBody
    public JSONObject save(@RequestBody QueryQo queryQo){
        queryQo.getBaseInfo().setCreateDate(simpleDateFormat.format(new Date()));
        this.baseInfoMapper.insert(queryQo.getBaseInfo());

        queryQo.getBdImportantMatter().setCreateDate(simpleDateFormat.format(new Date()));
        this.bdImportantMatterMapper.insert(queryQo.getBdImportantMatter());

        queryQo.getBdInfo().setCreateDate(simpleDateFormat.format(new Date()));
        this.bdInfoMapper.insert(queryQo.getBdInfo());

        for (DutyInfo dutyInfo : queryQo.getDutyInfos()) {
            dutyInfo.setCreateDate(simpleDateFormat.format(new Date()));
            this.dutyInfoMapper.insert(dutyInfo);
        }
        queryQo.getLineFailureInfo().setCreateDate(simpleDateFormat.format(new Date()));
        this.lineFailureInfoMapper.insert(queryQo.getLineFailureInfo());

        queryQo.getOnlineInspectionInfo().setCreateDate(simpleDateFormat.format(new Date()));
        this.onlineInspectionInfoMapper.insert(queryQo.getOnlineInspectionInfo());

        queryQo.getTomorrowBdInfo().setCreateDate(simpleDateFormat.format(new Date()));
        this.tomorrowBdInfoMapper.insert(queryQo.getTomorrowBdInfo());

        for (TomorrowDutyInfo tomorrowDutyInfo : queryQo.getTomorrowDutyInfo()) {
            tomorrowDutyInfo.setCreateDate(simpleDateFormat.format(new Date()));
            this.tomorrowDutyInfoMapper.insert(tomorrowDutyInfo);
        }

        for (EmergencyResponseInfo info : queryQo.getEmergencyResponseInfo()) {
            info.setCreateDate(simpleDateFormat.format(new Date()));
            this.emergencyResponseInfoMapper.insert(info);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", HttpStatus.OK.value());
        jsonObject.put("msg", "保存成功");
        return jsonObject;
    }


    @PostMapping("/loginIn")
    @ResponseBody
    public JSONObject loginIn(@RequestBody UserQo userQo){
        JSONObject jsonObject = new JSONObject();
        Map<String,Object> userMap =  new HashMap<>();
        userMap.put("username",userQo.getUsername());
        List<UserVo> userVos = this.userMapper.selectByMap(userMap);
        if (CollectionUtils.isEmpty(userVos)){
            jsonObject.put("msg", "用户名或密码错误");
            jsonObject.put("code",9999);
            return jsonObject;
        }
        UserVo userVo = userVos.get(0);

        String pwd = DigestUtils.md5DigestAsHex(userQo.getPassword().getBytes(StandardCharsets.UTF_8));


        if (pwd.equals(userVo.getPassword())){
            Map<String,String> map  = new HashMap<>();
            String accessToken = UUID.randomUUID().toString().replace("-", "");
            jsonObject.put("token", accessToken);
            jsonObject.put("code",HttpStatus.OK.value());
        }else {
            jsonObject.put("msg", "用户名或密码错误");
            jsonObject.put("code",9999);
        }
        return jsonObject;
    }
    @GetMapping("/doc")
    public String html(){
        return "index.html";
    }

    @GetMapping("/login")
    public String login(){
        return "login.html";
    }

    @GetMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        File file=new File("/opt/shudian/ribao/"+simpleDateFormat.format(new Date())+".docx");
        String fileName=file.getName();
        String ext=fileName.substring(fileName.lastIndexOf(".")+1);
        String agent=(String)request.getHeader("USER-AGENT"); //判断浏览器类型
        try {
            if(agent!=null && agent.indexOf("Fireforx")!=-1) {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");   //UTF-8编码，防止输出文件名乱码
            }
            else {
                fileName= URLEncoder.encode(fileName,"UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        BufferedInputStream bis=null;
        OutputStream os=null;
        response.reset();
        response.setCharacterEncoding("utf-8");
        if(ext=="docx") {
            response.setContentType("application/msword"); // word格式
        }else if(ext=="pdf") {
            response.setContentType("application/pdf"); // word格式
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);


        try {
            bis=new BufferedInputStream(new FileInputStream(file));
            byte[] b=new byte[bis.available()+1000];
            int i=0;
            os = response.getOutputStream();   //直接下载导出
            while((i=bis.read(b))!=-1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @GetMapping("/genWord")
    @ResponseBody
    public String down(){
        wordService.GenWord();
        return "";
    }

}